console.log('tax injected');
import { transformDataByOpenWeb } from './../../lib/openWebTransform.js';

let baseInfoCache;
window.onload = function () {
  // 登录填写账号密码
  if (/\/sword/g.test(window.location.pathname)) {
    window.postMessage({
      event: 'getBaseInfo'
    }, '*');
  }
};

window.addEventListener('message', async function ({ data }) {
  // 只监听来自于content script的信息
  if (data.sender !== 'content-script') {
    return false;
  }
  if (data.event === 'setSaasData') {
    fillInput(await transformDataByOpenWeb(data.data));
  }
  if (data.event === 'getNationData') {
    getNationData();
  }

  if (data.event === 'getBaseInfo') {
    baseInfoCache = data.data;
    autoInputAccount(baseInfoCache);
  }
}, false);

/**
 * 填充账号密码
 */
function autoInputAccount({ companyInfo }) {
  companyInfo = companyInfo || {};
  $('#name2').val(companyInfo.nationalTaxAccount || companyInfo.nationalTaxId);
  $('#pass2').val(companyInfo.nationalTaxPass);
}


/**
 * 调用接口获取公司信息
 */
function getNationData() {
  let taxInfo = {
    institution: '2013', // 国税对应制度 2007 | 2013
    nsrsbh: baseInfoCache.companyInfo.nationalTaxId, // 纳税人申报号
    nsrmc: baseInfoCache.companyInfo.companyName, // 纳税人名称（纳税公司）
    skssqq: '', // 税款所属期起
    skssqz: '', // 税款所属期止
    outPutType: 'xml', // 填报方式
    isZip: true,
    filesNum: 3
  };
  window.postMessage({
    event: 'backNationData',
    data: {
      taxInfo: taxInfo
    }
  }, '*');
}

function fillInput({ saasData, baseInfo }) {
  let message = '';
  if (saasData.data.type === 'file') {
    message = downloadFile(saasData.data.data, baseInfo);
  } else {
    message = '不支持json方式，下载文件失败！';
  }

  window.postMessage({
    event: 'fillInputDone',
    data: {
      message: message || '下载文件成功'
    }
  }, '*');
}

/**
 * 下载文件
 * @param blob
 */
// function downloadFile(blob, { taxInfo, popupParams }) {
//   blob = new Blob([blob], { type: 'text/xml' });
//   let a = document.createElement('a');
//   // 指定生成的文件名
//   // let name = `${taxInfo.nsrsbh}_${taxInfo.institution === '2013' ? 'ZL019' : 'ZL001'}`;
//   let name = '资产负债表';
//   let { nsrmc = '' } = taxInfo;
//   let { type } = popupParams;
//   type === 'cash' && (name = '现金流量表');
//   type === 'profit' && (name = '利润表');
//   const start = taxInfo.skssqq.replace(/-/g, '');
//   const end = taxInfo.skssqz.replace(/-/g, '');
//   a.download = `${nsrmc}_${name}_${start}_${end}.xml`;
//   a.href = URL.createObjectURL(blob);
//   document.body.appendChild(a);
//   a.click();
// }
function downloadFile(blob, { companyInfo, taxInfo, popupParams }) {
  blob = new Blob([blob], { type: 'application/vnd.ms-excel' });
  let a = document.createElement('a');
  // 指定生成的文件名
  let name = `${taxInfo.nsrmc}-三大报表-${companyInfo.curYear}-`;
  let curPeriod = companyInfo.curPeriod;
  name += curPeriod.length > 1 ? curPeriod : '0' + curPeriod;
  a.download = `${name}.zip`;
  a.href = URL.createObjectURL(blob);
  document.body.appendChild(a);
  a.click();
}
